package nancal.mp.config.base

import nbcp.base.extend.Slice
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.server.reactive.ServerHttpRequest
import java.lang.reflect.UndeclaredThrowableException

abstract class BaseFilter {
    @Value("\${app.filter.ignore-log-urls:/health}")
    var ignoreLogUrls: List<String> = listOf()

    @Value("\${app.filter.ignore-urls:/health}")
    var ignoreUrls: List<String> = listOf()


    fun getInnerException(e: Throwable): Throwable {
        var err = e;
        if (err is UndeclaredThrowableException) {
            return err.undeclaredThrowable;
        }

        if (err.cause != null) {
            return getInnerException(err.cause!!)
        }
        return err;
    }

    fun ServerHttpRequest.getHeader(headerName: String): String {
        return this.headers.getFirst(headerName) ?: ""
    }


    fun ignoreFilter(request: ServerHttpRequest): Boolean {
        return matchUri(request.path.value(), ignoreUrls)
    }

    fun ignoreLog(request: ServerHttpRequest): Boolean {
        return matchUri(request.path.value(), ignoreLogUrls)
    }


    private fun matchUri(requestURI: String, defineUris: List<String>): Boolean {
        return defineUris.any {
            var url = it;
            var exact = url.startsWith("(") && url.endsWith(")")
            if (exact) {
                url = url.Slice(1, -1);
            }

            if (url.startsWith("/") == false) {
                url = "/" + url;
            }
            if (exact) {
                return@any requestURI.startsWith(url, true)
            } else {
                return@any requestURI.equals(url, true)
            }
        }
    }

}